<template>
  <div class="clearfix">
    <a-upload
      :accept="uploadAccept"
      list-type="picture-card"
      class="avatar-uploader"
      :file-list="fileList"
      :customRequest="upload"
      :before-upload="beforeBusinessLicenseUpload"
      @preview="handleSkuPicPreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < picLimit">
        <a-icon :type="picLoading ? 'loading' : 'plus'"/>
        <div class="ant-upload-text">
          上传
        </div>
      </div>
    </a-upload>

    <p style="line-height: 15px; font-size: 10px; color: gray;">{{ prompt }}支持{{ uploadAccept.split(',').map(accept =>
      accept.substring(1)).join('、') }}格式的媒体，文件不可超过{{ sizeLimit / (1024 ** 2) }}MB。</p>

    <a-modal :visible="skuPicPreviewVisible" :footer="null" @cancel="handleSkuPreviewCancel">
      <img
        v-if="skuPicPreviewObj !== null && skuPicPreviewObj.mime_type.indexOf('image') !== -1"
        style="width: 100%"
        :src="skuPicPreviewObj.url"
      />

      <video
        v-if="skuPicPreviewObj !== null && skuPicPreviewObj.mime_type.indexOf('video') !== -1"
        width="320"
        height="240"
        controls
      >
        <source :src="skuPicPreviewObj.url" :type="skuPicPreviewObj.mime_type">
        您的浏览器不支持Video标签。
      </video>
    </a-modal>
  </div>
</template>

<script>
import { uploadAttachment } from '@/api/attachment'
import { getImgBase64 } from '@/utils/util'
import lrz from 'lrz'

export default {
    name: 'UploadPic',
    props: {
      limit: {
        type: Number,
        default: 1
      },
      value: {
        type: Array,
        default: () => []
      },
      wechatMaterial: {
        type: Boolean,
        default: false
      },
      accept: {
        type: String,
        default: '.jpg,.png,.jpeg'
      },
      size: {
        type: Number,
        default: 5 * (1024 ** 2) // 5M
      },
      tips: {
        type: String,
        default: ''
      },
      // preview 钩子
      preview: {
        type: Function,
        default: () => {
          return new Promise(resolve => {
            resolve()
          })
        }
      }
    },
    data () {
      return {
        skuPicPreviewVisible: false,
        skuPicPreviewObj: null,
        picLimit: this.limit,
        picLoading: false,
        fileList: [],
        uploadAccept: this.accept,
        sizeLimit: this.size,
        prompt: this.tips
      }
    },
    watch: {
      value: {
        handler: function (val) {
          if (val !== null) {
            this.fileList = val
          }
        },
        immediate: true
      }
    },
    methods: {
      async upload (customRequest) {
        if (customRequest.file.type.indexOf('image') !== -1) {
          // 当图片上传时, 压缩
          return lrz(customRequest.file).then(rst => {
            return uploadAttachment(rst.file, this.wechatMaterial ? 1 : 2).then(res => {
              customRequest.onSuccess(res.attachment)
            })
          }).catch(e => {
            return uploadAttachment(customRequest.file, this.wechatMaterial ? 1 : 2).then(res => {
              customRequest.onSuccess(res.attachment)
            })
          })
        } else {
          return uploadAttachment(customRequest.file, this.wechatMaterial ? 1 : 2).then(res => {
            customRequest.onSuccess(res.attachment)
          })
        }
      },
      handleSkuPicPreview (file) {
        this.preview(file)
          .then(_ => {
            this.skuPicPreviewVisible = true
            this.skuPicPreviewObj = file
          })
          .catch(e => {
            // nothing
          })
      },
      handleSkuPreviewCancel () {
        this.skuPicPreviewVisible = false
      },
      handleChange (fileList) {
        switch (fileList.file.status) {
          case 'uploading':
            this.picLoading = true
            break
          case 'done':
            getImgBase64(fileList.file.originFileObj, imageUrl => {
              this.pic = imageUrl
              this.picLoading = false
            })
            break
          case 'error':
            this.$message.error('媒体上传发生错误')
            break
          case 'removed':
            this.pic = ''
            break
          default:
            return
        }

        var result = fileList.fileList.slice(-1 * this.picLimit).map(file => {
          if (file.response) {
            file.url = file.response.url
            file.mime_type = file.response.mime_type
          }
          return file
        })

        this.fileList = result
        this.$emit('change', result)

        return result
      },
      beforeBusinessLicenseUpload (file) {
        const validateXlsAccept = (this.uploadAccept.split(',').indexOf('.xls') >= 0) && (file.type === 'application/vnd.ms-excel')
        const validateXlsxAccept = (this.uploadAccept.split(',').indexOf('.xlsx') >= 0) && (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        const validatePicAccept = (this.uploadAccept.split(',').map(accept => 'image/' + accept.substring(1)).indexOf(file.type) >= 0)
        const validateVideoAccept = (this.uploadAccept.split(',').map(accept => 'video/' + accept.substring(1)).indexOf(file.type) >= 0) // 简单的扩展下视频验证

        if (!validatePicAccept && !validateVideoAccept && !validateXlsAccept && !validateXlsxAccept) {
          this.$message.error(`只能上传${this.uploadAccept.split(',').map(accept => accept.substring(1)).join('、')}格式媒体`)
        }
        const isLtSizeLimit = file.size < this.sizeLimit
        if (!isLtSizeLimit) {
          this.$message.error(`媒体大小必须小于${this.sizeLimit / (1024 ** 2)}M`)
        }

        return (validatePicAccept || validateVideoAccept || validateXlsAccept || validateXlsxAccept) && isLtSizeLimit
      }
    }
  }
</script>

<style scoped>

</style>
